<template>
	<view class="kui-grid-item kui-flex kui-flex-col kui-items-center kui-box-border" :style="rootStyle" @click="onClick">
		<view :style="contentStyle">
			<slot>
				<view>
					<slot name="icon">
						<kui-icons :type="icon" :color="state.iconColor" :size="state.iconSize"></kui-icons>
					</slot>
				</view>
				<view :class="[parent.reverse ? 'kui-mb-2' : '', parent.direction == 'horizontal' ? 'kui-ml-2' : 'kui-mt-2']">
					<slot name="text">
						<kui-text :size="state.fontSize">{{ text }}</kui-text>
					</slot>
				</view>
			</slot>
		</view>
	</view>
</template>

<script lang="ts">
	import {
		reactive,
		inject,
		defineComponent,
		SetupContext,
		computed,
		CSSProperties,
		toRefs,
		getCurrentInstance,
		onMounted
	} from 'vue';
	
	import GridItemProps from './props';
	
	const name = 'kui-grid-item';
	
	export default defineComponent({
		name,
		props: GridItemProps,
		emits: ['click'],
		setup(props, context: SetupContext) {
			const parent = inject('kui-grid');
			// console.log(parent);
			if (!parent) return;
			const {
				proxy
			}: any = getCurrentInstance();
			const theme = proxy.$theme;
			
			const state = reactive({
				iconSize: parent.iconSize,
				iconColor: props.iconColor ? props.iconColor : parent.iconColor,
				showRightBorder: true,
				showTopBorder: false,
				fontSize: `${theme.size.fonts.sm}rpx`,
				marginRight: ''
			});
			
			if (props.iconSize > parent.iconSize) {
				state.iconSize = props.iconSize
			}
			
			const rootStyle = computed(() => {
				const style: CSSProperties = reactive({});
				style.backgroundColor = '#FFFFFF';
				const borderColor = theme.colors['light']['grey'][3];
				const borderWidth = '1rpx';
				const borderStyle = 'solid';
				const border = `${borderWidth} ${borderStyle} ${borderColor}`;
				style.borderRight = state.showRightBorder ? border : '';
				style.borderTop = state.showTopBorder ? border : '';
				style.marginRight = state.marginRight;
				style.height = '100%';
				return style;
			});
			
			const contentStyle = computed(() => {
				const style: CSSProperties = reactive({});
				style.lineHeight = 1;
				style.textAlign = 'center';
				style.margin = '32rpx 0rpx';
				style.display = 'flex';
				style.flexDirection = 'column';
				if (parent.reverse) {
					style.flexDirection = 'column-reverse';
				}
				if (parent.direction == 'horizontal') {
					style.flexDirection = 'row';
					style.alignItems = 'center';
				}
				
				return style;
			});
			
			onMounted(() => {
				// 判断有无父元素实例
				if (parent && parent.childrens.indexOf(state) === -1) {
					parent.childrens.push(state);
				}
			});
			
			const onClick = () => {
				if (!parent.clickable) return;
				context.emit('click', props.id);
			}
			
			return {
				state,
				rootStyle,
				contentStyle,
				parent,
				onClick
			}
		}
	});
</script>

<style>

</style>